// 0. 导入 vue
import Vue from 'vue'

// 1. 导入路由
import VueRouter from 'vue-router'
import Home from '@/components/home/Home.vue'
import Login from '@/components/login/Login.vue'
import Users from '@/components/users/Users.vue'
import Roles from '@/components/roles/Roles.vue'
import Rights from '@/components/rights/Rights.vue'
import Categories from '@/components/categories/Categories.vue'
import Goods from '@/components/goods/Goods.vue'
import GoodsAdd from '@/components/goods-add/Goods-add.vue'

// 2. 当成插件安装
Vue.use(VueRouter)

// 3. 实例化路由 路由配置
const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    {
      path: '/home',
      component: Home,
      // 子路由 放在 children 里
      children: [
        { path: '/users', component: Users },
        { path: '/roles', component: Roles },
        { path: '/rights', component: Rights },
        { path: '/categories', component: Categories },
        { path: '/goods/:page?', component: Goods },
        { path: '/goods-add', component: GoodsAdd }
      ]
    }
  ]
})
// 导航首位
router.beforeEach((to, from, next) => {
  // console.log('to:', to)
  // console.log('from:', from)

  // 判断是否登录页面
  // 是登录页面
  if (to.path === '/login') {
    next()
  } else {
    // 不是登录页面
    // 判断是否登录
    // 获取 token
    const token = localStorage.getItem('token')

    if (token) {
      next()
    } else {
      next('/login')
    }
  }
})

// 导出 router
export default router
